
package org.buildforce.tomcat.util;

import org.apache.maven.model.FileSet;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.shared.model.fileset.util.FileSetManager;
import org.codehaus.plexus.util.DirectoryScanner;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * Copyright 2001-2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 *
 * NOTE:    Beware of org.apache.maven.shared.model.fileset.FileSet
 *          vs. org.apache.maven.model.FileSet
 *
 * @author  Martin Todorov
 */
public class FileSystemUtils
{

    /**
     * Default includes - everything is included.
     */
    private static final String[] DEFAULT_INCLUDES = {"**/**"};


    /**
     * Copies given resources to the build directory.
     *
     * @param resources
     * @param log
     * @throws MojoExecutionException
     */
    public static void copyResources(Resource[] resources, Log log)
            throws MojoExecutionException
    {
        final String[] emptyStrArray = {};

        for (Resource resource : resources)
        {
            FileSet fileSet = new FileSet();
            fileSet.setDirectory(resource.getDirectory());

            for (Object include : resource.getIncludes())
                fileSet.addInclude((String) include);

            for (Object exclude : resource.getExcludes())
                fileSet.addExclude((String) exclude);

            File resourceDirectory = new File(fileSet.getDirectory());
            if (!resourceDirectory.isAbsolute())
                resourceDirectory = new File(resourceDirectory.getPath());

            if (!resourceDirectory.exists())
            {
                log.info("Additional resource directory does not exist: " + resourceDirectory);
                continue;
            }

            DirectoryScanner scanner = new DirectoryScanner();

            scanner.setBasedir(resourceDirectory);
            if (fileSet.getIncludes() != null && !fileSet.getIncludes().isEmpty())
                //noinspection unchecked
                scanner.setIncludes((String[]) fileSet.getIncludes().toArray(emptyStrArray));
            else
                scanner.setIncludes(DEFAULT_INCLUDES);

            if (fileSet.getExcludes() != null && !fileSet.getExcludes().isEmpty())
                //noinspection unchecked
                scanner.setExcludes((String[]) fileSet.getExcludes().toArray(emptyStrArray));

            scanner.addDefaultExcludes();
            scanner.scan();

            List includedFiles = Arrays.asList(scanner.getIncludedFiles());

            log.info("Copying " + includedFiles.size() + " web resource" + (includedFiles.size() > 1 ? "s" : ""));

            for (Object includedFile : includedFiles)
            {
                String destination = (String) includedFile;
                File source = new File(resourceDirectory, destination);
                File destinationFile = new File(resource.getTargetPath(), destination);

                if (!destinationFile.getParentFile().exists())
                    destinationFile.getParentFile().mkdirs();

                try
                {
                    org.codehaus.plexus.util.FileUtils.copyFile(source, destinationFile);
                }
                catch (IOException e)
                {
                    throw new MojoExecutionException("Error copying web resource " + source, e);
                }
            }
        }
    }

    /**
     * Deletes a directory and its contents.
     *
     * @param dir The base directory of the included and excluded files.
     * @throws MojoExecutionException When a directory failed to get deleted.
     */
    public static void removeDirectory(File dir, Log log)
            throws MojoExecutionException
    {
        if (dir != null)
        {
            org.apache.maven.shared.model.fileset.FileSet fs = new org.apache.maven.shared.model.fileset.FileSet();
            fs.setDirectory(dir.getPath());
            fs.addInclude("**");

            removeFileSet(fs, log);
        }
    }

    /**
     * Deletes the specified file set. If the base directory of the file set is relative, it will be resolved against
     * the base directory of the current project.
     *
     * @param fileset The file set to delete, must not be <code>null</code>.
     * @throws MojoExecutionException When the file set failed to get deleted.
     */
    public static void removeFileSet(org.apache.maven.shared.model.fileset.FileSet fileset, Log log)
            throws MojoExecutionException
    {
        try
        {
            File dir = new File(fileset.getDirectory()).getAbsoluteFile();

            if (!dir.exists())
            {
                log.debug("Skipping non-existing directory: " + dir);
                return;
            }

            if (!dir.isDirectory())
            {
                throw new MojoExecutionException(dir + " is not a directory.");
            }

            log.info("Deleting " + fileset.getDirectory());
            FileSetManager fileSetManager = new FileSetManager(log, true);
            fileSetManager.delete(fileset);
        }
        catch (IOException e)
        {
            throw new MojoExecutionException("Failed to delete directory: " + fileset.getDirectory() + ". Reason: "
                                             + e.getMessage(), e);
        }
        catch (IllegalStateException e)
        {
            // TODO: IOException from plexus-utils should be acceptable here
            throw new MojoExecutionException("Failed to delete directory: " + fileset.getDirectory() + ". Reason: "
                                             + e.getMessage(), e);
        }
    }

    public static org.apache.maven.shared.model.fileset.FileSet createFileSet(File directory, String[] includes, String[] excludes)
    {
        return createFileSet(directory.getPath(), includes, excludes);
    }

    public static org.apache.maven.shared.model.fileset.FileSet createFileSet(String directory, String includes, String excludes)
    {
        String[] inc = includes != null ? includes.split(",") : null;
        String[] exc = excludes != null ? excludes.split(",") : null;

        return createFileSet(directory, inc, exc);
    }

    public static org.apache.maven.shared.model.fileset.FileSet createFileSet(String directory, String[] includes, String[] excludes)
    {
        org.apache.maven.shared.model.fileset.FileSet fileSet = new org.apache.maven.shared.model.fileset.FileSet();
        fileSet.setDirectory(directory);

        if (includes != null)
        {
            for (String include : includes)
            {
                fileSet.addInclude(include);
            }
        }

        if (excludes != null)
        {
            for (String exclude : excludes)
            {
                fileSet.addExclude(exclude);
            }
        }

        return fileSet;
    }

}
